package com.haha.sum;

import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.Word;
import org.jnativehook.GlobalScreen;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.*;

/**
 * @author shenlinnan
 * @date 2025/7/27 16:04
 */
public class Test1 implements NativeKeyListener {

    // 配置参数
    private static final String IMAGE_PATH = "I:\\my-workspace\\haha-maven\\screenshots\\screenshot_20250727-171422.png";
    // 修正语言数据路径 - 指向包含 eng.traineddata 的目录
    private static final String TESSDATA_PATH = "I:\\my-workspace\\haha-maven\\src\\main\\resources";
    private static final String LANGUAGE = "eng"; // 英文识别

    public static void main(String[] args) throws AWTException {
        try {
            // 配置并注册全局键盘钩子
            GlobalScreen.registerNativeHook();
            GlobalScreen.addNativeKeyListener(new Test1());

            // 禁用JNativeHook日志
            java.util.logging.Logger.getLogger(GlobalScreen.class.getPackage().getName())
                    .setLevel(java.util.logging.Level.OFF);
            System.out.println("配置键盘监听器已注册");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void nativeKeyTyped(NativeKeyEvent nativeKeyEvent) {

    }

    @Override
    public void nativeKeyPressed(NativeKeyEvent nativeKeyEvent) {
        if (nativeKeyEvent.getKeyCode() == NativeKeyEvent.VC_F11) {
            java.awt.Point mousePos = java.awt.MouseInfo.getPointerInfo().getLocation();
            System.out.println("mousePos==" + mousePos);
            // 截取屏幕
            Robot robot = null;
            try {
                robot = new Robot();
            } catch (AWTException e) {
                e.printStackTrace();
            }
            // 怀旧巫妖王
            Rectangle screenRect = new Rectangle(378, 304, 222, 30);
//            Rectangle screenRect = new Rectangle(277, 242, 222, 23);
            BufferedImage screenCapture = robot.createScreenCapture(screenRect);

            // 保存截图到本地
            try {
                saveScreenshot(screenCapture);
            } catch (IOException e) {
                e.printStackTrace();
            }

            ITesseract tesseract = new Tesseract();
            tesseract.setDatapath(TESSDATA_PATH);
            tesseract.setLanguage(LANGUAGE);
            List<Word> words = tesseract.getWords(screenCapture, ITesseract.RenderedFormat.TEXT.ordinal());
            Word word = words.get(0);

            String text = word.getText();
            String cleanedText = text
                    // Windows格式
                    .replace("\r\n", "")
                    // Unix格式
                    .replace("\n", "")
                    // 旧版Mac格式
                    .replace("\r", "");
            System.out.println("----text==" + cleanedText + "----");


            Set<String> namesToFind = new HashSet<>();
            int sum = 0;
            int paladinSum = 0;
            int deathKnightSum = 0;
            int hunterSum = 0;
            int monkSum = 0;
            int shamanSum = 0;
            int priestSum = 0;
            int mageSum = 0;
            int warriorSum = 0;
            int druidSum = 0;
            int warlockSum = 0;
            int rogueSum = 0;
            int sameNameCount = 0;
            while (true) {
                // 截取图片
                screenRect = new Rectangle(378, 304, 222, 30);
                screenCapture = robot.createScreenCapture(screenRect);

                int width = screenCapture.getWidth();

                Color warriorColor = new Color(212, 168, 123);
                Color paladinColor = new Color(255, 152, 199);
                Color hunterColor = new Color(184, 224, 128);
                Color deathKnightColor = new Color(209, 43, 72);
                Color monkColor = new Color(13, 255, 163);
                Color shamanColor = new Color(13, 124, 235);
                Color priestColor = new Color(255, 255, 255);
                Color mageColor = new Color(77, 211, 248);
                Color druidColor = new Color(255, 137, 23);
                Color warlockColor = new Color(148, 147, 250);
                Color rogueColor = new Color(255, 255, 118);
                for (int i = 0; i < width; i++) {
                    int rgb = screenCapture.getRGB(i, 11);
                    Color color = new Color(rgb);
                    if (warriorColor.equals(color)) {
                        warriorSum++;
                        break;
                    }
                    if (paladinColor.equals(color)) {
                        paladinSum++;
                        break;
                    }
                    if (hunterColor.equals(color)) {
                        hunterSum++;
                        break;
                    }
                    if (deathKnightColor.equals(color)) {
                        deathKnightSum++;
                        break;
                    }
                    if (monkColor.equals(color)) {
                        monkSum++;
                        break;
                    }
                    if (shamanColor.equals(color)) {
                        shamanSum++;
                        break;
                    }
                    if (priestColor.equals(color)) {
                        priestSum++;
                        break;
                    }
                    if (mageColor.equals(color)) {
                        mageSum++;
                        break;
                    }
                    if (druidColor.equals(color)) {
                        druidSum++;
                        break;
                    }
                    if (warlockColor.equals(color)) {
                        warlockSum++;
                        break;
                    }
                    if (rogueColor.equals(color)) {
                        rogueSum++;
                        break;
                    }
                }

                sum++;

                // 点击左键
                robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
                robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);

                // 获取文本
                words = tesseract.getWords(screenCapture, ITesseract.RenderedFormat.TEXT.ordinal());
                if (words.size() <= 0) {
                    continue;
                }
                word = words.get(0);
                text = word.getText();
                cleanedText = text
                        // Windows格式
                        .replace("\r\n", "")
                        // Unix格式
                        .replace("\n", "")
                        // 旧版Mac格式
                        .replace("\r", "");

                // 对比一下set中是否已经有这个角色了
                if (namesToFind.contains(cleanedText)) {
                    System.out.println("重复的姓名,cleanedText=" + cleanedText);
                    sameNameCount++;
                    if (sameNameCount > 3) {
                        break;
                    }
                    continue;
                }
                // 将姓名放到set中
                namesToFind.add(cleanedText);
                sameNameCount = 0;

                robot.delay(100);
            }
            System.out.println("总共" + sum + "个角色");
            System.out.println("圣骑士总共：" + paladinSum + "个");
            System.out.println("死亡骑士总共：" + deathKnightSum + "个");
            System.out.println("猎人总共：" + hunterSum + "个");
            System.out.println("武僧总共：" + monkSum + "个");
            System.out.println("萨满祭司总共：" + shamanSum + "个");
            System.out.println("牧师总共：" + priestSum + "个");
            System.out.println("法师总共：" + mageSum + "个");
            System.out.println("战士总共：" + warriorSum + "个");
            System.out.println("德鲁伊总共：" + druidSum + "个");
            System.out.println("术士总共：" + warlockSum + "个");
            System.out.println("潜行者总共：" + rogueSum + "个");

            int allSum = paladinSum + deathKnightSum + hunterSum + monkSum + shamanSum + priestSum + mageSum + warriorSum + druidSum + warlockSum + rogueSum;
            System.out.println("统计到的职业有：" + allSum);

            Map<String, Integer> data = new HashMap<>();
            data.put("圣骑士", paladinSum);
            data.put("死亡骑士", deathKnightSum);
            data.put("猎人", hunterSum);
            data.put("武僧", monkSum);
            data.put("萨满祭司", shamanSum);
            data.put("牧师", priestSum);
            data.put("法师", mageSum);
            data.put("战士", warriorSum);
            data.put("德鲁伊", druidSum);
            data.put("术士", warlockSum);
            data.put("潜行者", rogueSum);

            // 转换为Entry列表并按值降序排序
            List<Map.Entry<String, Integer>> entries = new ArrayList<>(data.entrySet());
            entries.sort(Map.Entry.<String, Integer>comparingByValue().reversed());

            // 输出结果
            System.out.println("使用Map.Entry排序：");
            entries.forEach(entry ->
                    System.out.println(entry.getKey() + ": " + entry.getValue())
            );
        }

    }


    @Override
    public void nativeKeyReleased(NativeKeyEvent nativeKeyEvent) {

    }

    /**
     * 保存截图到本地磁盘
     *
     * @param image 要保存的图像
     */
    private void saveScreenshot(BufferedImage image) throws IOException {
        // 创建保存目录（如果不存在）
        File dir = new File("screenshots");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 生成带时间戳的文件名
        String timestamp = new java.text.SimpleDateFormat("yyyyMMdd-HHmmss").format(new java.util.Date());
        String fileName = "screenshot_" + timestamp + ".png";
        File outputFile = new File(dir, fileName);

        // 将图像保存为PNG格式
        ImageIO.write(image, "png", outputFile);

        System.out.println("截图已保存至: " + outputFile.getAbsolutePath());
    }
}
